/**
 * 聊天相关组合式函数
 */
import { ref, computed, nextTick } from "vue";
import { useChatStore } from "@/stores/chat";
import { ElMessage } from "element-plus";
import type {
  ChatMessage,
  ChatSession,
  SendMessageRequest,
} from "@/types/chat";

export function useChat() {
  const chatStore = useChatStore();

  const loading = ref(false);
  const sending = ref(false);
  const inputText = ref("");
  const isTyping = ref(false);
  const attachments = ref<File[]>([]);

  // 计算属性
  const currentSession = computed(() => chatStore.currentSession);
  const messages = computed(() => chatStore.messages);
  const sessions = computed(() => chatStore.sessions);
  const personas = computed(() => chatStore.personas);
  const currentPersona = computed(() => chatStore.currentPersona);

  // 发送消息
  const sendMessage = async (content?: string, files?: File[]) => {
    try {
      if (sending.value) return false;

      const messageContent = content || inputText.value.trim();
      const messageFiles = files || attachments.value;

      if (!messageContent && messageFiles.length === 0) {
        ElMessage.warning("请输入消息内容");
        return false;
      }

      if (!currentSession.value) {
        ElMessage.warning("请先选择或创建会话");
        return false;
      }

      sending.value = true;

      const messageData: SendMessageRequest = {
        sessionId: currentSession.value.id,
        content: messageContent,
        type: messageFiles.length > 0 ? "multimodal" : "text",
        attachments: messageFiles.map((file) => ({
          name: file.name,
          size: file.size,
          type: file.type,
          url: URL.createObjectURL(file),
        })),
      };

      await chatStore.sendMessage(messageData);

      // 清空输入
      inputText.value = "";
      attachments.value = [];

      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "发送消息失败");
      return false;
    } finally {
      sending.value = false;
    }
  };

  // 发送流式消息
  const sendStreamMessage = async (content?: string, files?: File[]) => {
    try {
      if (sending.value) return false;

      const messageContent = content || inputText.value.trim();
      const messageFiles = files || attachments.value;

      if (!messageContent && messageFiles.length === 0) {
        ElMessage.warning("请输入消息内容");
        return false;
      }

      if (!currentSession.value) {
        ElMessage.warning("请先选择或创建会话");
        return false;
      }

      sending.value = true;

      const messageData: SendMessageRequest = {
        sessionId: currentSession.value.id,
        content: messageContent,
        type: messageFiles.length > 0 ? "multimodal" : "text",
        attachments: messageFiles.map((file) => ({
          name: file.name,
          size: file.size,
          type: file.type,
          url: URL.createObjectURL(file),
        })),
        stream: true,
      };

      await chatStore.sendStreamMessage(messageData);

      // 清空输入
      inputText.value = "";
      attachments.value = [];

      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "发送消息失败");
      return false;
    } finally {
      sending.value = false;
    }
  };

  // 创建新会话
  const createSession = async (title?: string, personaId?: string) => {
    try {
      loading.value = true;

      const sessionData = {
        title: title || "新对话",
        personaId: personaId || currentPersona.value?.id,
      };

      const session = await chatStore.createSession(sessionData);
      await chatStore.selectSession(session.id);

      return session;
    } catch (error: any) {
      ElMessage.error(error.message || "创建会话失败");
      return null;
    } finally {
      loading.value = false;
    }
  };

  // 选择会话
  const selectSession = async (sessionId: string) => {
    try {
      loading.value = true;
      await chatStore.selectSession(sessionId);
      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "切换会话失败");
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 删除会话
  const deleteSession = async (sessionId: string) => {
    try {
      await chatStore.deleteSession(sessionId);
      ElMessage.success("会话已删除");
      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "删除会话失败");
      return false;
    }
  };

  // 切换人格
  const switchPersona = async (personaId: string) => {
    try {
      loading.value = true;
      await chatStore.switchPersona(personaId);
      ElMessage.success("人格切换成功");
      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "切换人格失败");
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 重新生成消息
  const regenerateMessage = async (messageId: string) => {
    try {
      sending.value = true;
      await chatStore.regenerateMessage(messageId);
      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "重新生成失败");
      return false;
    } finally {
      sending.value = false;
    }
  };

  // 编辑消息
  const editMessage = async (messageId: string, content: string) => {
    try {
      await chatStore.editMessage(messageId, content);
      ElMessage.success("消息已更新");
      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "编辑消息失败");
      return false;
    }
  };

  // 删除消息
  const deleteMessage = async (messageId: string) => {
    try {
      await chatStore.deleteMessage(messageId);
      ElMessage.success("消息已删除");
      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "删除消息失败");
      return false;
    }
  };

  // 添加附件
  const addAttachment = (file: File) => {
    // 检查文件大小和类型
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      ElMessage.error("文件大小不能超过10MB");
      return false;
    }

    const allowedTypes = [
      "image/",
      "audio/",
      "video/",
      "application/pdf",
      "text/",
    ];
    if (!allowedTypes.some((type) => file.type.startsWith(type))) {
      ElMessage.error("不支持的文件类型");
      return false;
    }

    attachments.value.push(file);
    return true;
  };

  // 移除附件
  const removeAttachment = (index: number) => {
    attachments.value.splice(index, 1);
  };

  // 清空附件
  const clearAttachments = () => {
    attachments.value = [];
  };

  // 滚动到底部
  const scrollToBottom = async () => {
    await nextTick();
    const chatContainer = document.querySelector(".chat-messages");
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight;
    }
  };

  // 标记消息已读
  const markAsRead = async (sessionId: string) => {
    try {
      await chatStore.markAsRead(sessionId);
      return true;
    } catch (error) {
      return false;
    }
  };

  // 搜索消息
  const searchMessages = async (query: string, sessionId?: string) => {
    try {
      loading.value = true;
      const results = await chatStore.searchMessages(query, sessionId);
      return results;
    } catch (error: any) {
      ElMessage.error(error.message || "搜索失败");
      return [];
    } finally {
      loading.value = false;
    }
  };

  // 导出会话
  const exportSession = async (
    sessionId: string,
    format: "json" | "txt" | "pdf" = "json",
  ) => {
    try {
      loading.value = true;
      const data = await chatStore.exportSession(sessionId, format);

      // 下载文件
      const blob = new Blob([data], {
        type: format === "json" ? "application/json" : "text/plain",
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `chat-session-${sessionId}.${format}`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      ElMessage.success("导出成功");
      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "导出失败");
      return false;
    } finally {
      loading.value = false;
    }
  };

  return {
    // 状态
    loading,
    sending,
    inputText,
    isTyping,
    attachments,
    currentSession,
    messages,
    sessions,
    personas,
    currentPersona,

    // 方法
    sendMessage,
    sendStreamMessage,
    createSession,
    selectSession,
    deleteSession,
    switchPersona,
    regenerateMessage,
    editMessage,
    deleteMessage,
    addAttachment,
    removeAttachment,
    clearAttachments,
    scrollToBottom,
    markAsRead,
    searchMessages,
    exportSession,
  };
}
